package net.zoneland.zrdp.framework.security.handle;

import java.io.IOException;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import net.zoneland.zrdp.common.constant.Constants;
import net.zoneland.zrdp.common.core.domain.AjaxResult;
import net.zoneland.zrdp.common.core.domain.model.LoginUser;
import net.zoneland.zrdp.common.utils.JacksonUtils;
import net.zoneland.zrdp.common.utils.ServletUtils;
import net.zoneland.zrdp.framework.manager.AsyncManager;
import net.zoneland.zrdp.framework.manager.factory.AsyncFactory;
import net.zoneland.zrdp.framework.web.service.TokenService;

/**
 * 自定义退出处理类 返回成功
 *
 * @author zonevue
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Resource
    private TokenService tokenService;

    /**
     * 退出处理
     *
     */
    @Override
    public void onLogoutSuccess(final  HttpServletRequest request, final HttpServletResponse response, final Authentication authentication)
            throws IOException {
        final LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.nonNull(loginUser))
        {
            final String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser);
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
            final HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
        }
        ServletUtils.renderString(response, JacksonUtils.toJsonString(AjaxResult.success("退出成功")));
    }
}
